package com.warmlight.voicepacket;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.warmlight.voicepacket.adapter.CommentDetailAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.bean.cdetails.CDetailsListBean;
import com.warmlight.voicepacket.bean.comm.RecommPictureBean;
import com.warmlight.voicepacket.data.ReplyListBean;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.communitylm.widget.ReplyBar;
import com.warmlight.voicepacket.ui.communitylm.widget.ReplyBarBase;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 评论的评论列表页面
 */
public class CommentDetailAcitivity extends BaseActivity{
    private RecyclerView comment_rl;
    private CommentDetailAdapter adapter = null;
    private List<ReplyListBean.ListBean> list = new ArrayList<>();
    private int page = 1;
    private TextView tv_title;
    private ImageView iv_closecha;
    private ReplyBar replyBar;
    private  String post_id;
    private  String reply_id;
    private String uid;
    private RefreshLayout refreshLayout;
    private String type;
    private Map<String, String> item;
    private String replynum;
    private TextView tv_nodata;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_commentdetial);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            post_id = bundle.getString("post_id");
            reply_id = bundle.getString("reply_id");
            uid = bundle.getString("uid");

            if (bundle.containsKey("type")){
                type = bundle.getString("type");
                item = (Map<String, String>) bundle.getSerializable("msg");
            }
        }
        initView();
        initReplyBar();
        initData(true);
    }


    private void msgType(){
        if (!TextUtils.isEmpty(type) && item != null){
            String id = item.get("id");//消息id
            String uid = item.get("uid");//接收者UID
            String content = item.get("content");//消息内容
            String jump_page = item.get("jump_page");//消息跳转页面：1帖子2评论3发布的音频
            String pic = item.get("pic");//对应的图片，空为无图片，否则为图片地址
            String related_id = item.get("related_id");//跳转到对应的id
            String send_uid = item.get("send_uid");//发送者的uid
            String add_time = item.get("add_time");//添加时间戳
            String read_time = item.get("read_time");//读取时间
            String update_time = item.get("update_time");//更新时间
            String author = item.get("author");//发送者的用户信息
            String datetime = item.get("datetime");//发送时间，前端显示用
            String a_uid = "";
            String a_nickname = "";
            String a_avator = "";
            String a_sex = "";
            String a_sign = "";
            //对我评论的人的信息
            if (!TextUtils.isEmpty(author)) {
                ArrayList<Map<String, String>> authors = JSONUtils.getListMapByJson(author);
                if (authors.size() > 0) {
                    Map<String, String> map = authors.get(0);
                    a_uid = map.get("uid");
                    a_nickname = map.get("nickname");
                    a_avator = map.get("avator");
                    a_sex = map.get("sex");
                    a_sign = map.get("sign");
                }
            }

            /**
             * "comment_res":{
             "id":"88314",
             "pics":[

             ],
             "content":"急急急",
             "status":"2",
             "post_id":"2409",
             "reply_id":"0"
             }
             */

            //帖子的评论
//            final String comment_res = item.get("comment_res");
//            String comment_res_id = "";
//            String coment_res_pics = "";
//            String coment_res_content = "";
//            String coment_res_post_id = "";
//            if (!TextUtils.isEmpty(comment_res)) {
//                ArrayList<Map<String, String>> comment_res_list = JSONUtils.getListMapByJson(comment_res);
//                if (comment_res_list.size() > 0) {
//                    Map<String, String> map = comment_res_list.get(0);
//                    comment_res_id = map.get("id");
//                    coment_res_pics = map.get("pics");
//                    coment_res_content = map.get("content");
//                    coment_res_post_id = map.get("post_id");
//                }
//            }


            //别人回复你的信息
            final String reply_res = item.get("reply_res");
            String reply_res_content = "";//别人回复我的信息
            String reply_res_id = "";//回复的回复的id
//            String reply_id = "";//帖子评论的id
            String reply_res_pics = "";
            if (!TextUtils.isEmpty(reply_res)) {
                ArrayList<Map<String, String>> reply_ress = JSONUtils.getListMapByJson(reply_res);
                if (reply_ress.size() > 0) {
                    Map<String, String> map = reply_ress.get(0);
                    reply_res_id = map.get("id");
                    reply_res_content = map.get("content");
                    String status = map.get("status");
                    String post_id = map.get("post_id");
//                    reply_id = map.get("reply_id");
                    reply_res_pics = map.get("pics");
                }
            }
            //当前帖子的信息，展示右侧的图片或者文字
//        String post_res = item.get("post_res");
//        String post_res_content = "";//右侧文字 没有图片就展示文字
//        String pic_right = "";//右侧图片
//        String post_res_id = "";//帖子的id
//        if (!TextUtils.isEmpty(post_res)){
//            ArrayList<Map<String, String>> post_res_list = JSONUtils.getListMapByJson(post_res);
//            if (post_res_list.size()>0){
//                Map<String, String> map = post_res_list.get(0);
//                post_res_id = map.get("id");
//                post_res_content = map.get("content");
//                String category = map.get("category");//1 图文 2 视频
//                if (TextUtils.equals("1",category)){
//                    String post_res_pics = map.get("pics");
//                    ArrayList<Map<String, String>> pics = JSONUtils.getListMapByJson(post_res_pics);
//                    if (pics.size()>0){
//                        Map<String, String> map1 = pics.get(0);
//                        pic_right = map1.get("");
//                    }
//                }else{
//                    String post_res_video = map.get("video");
//                    ArrayList<Map<String, String>> videos = JSONUtils.getListMapByJson(post_res_video);
//                    if (videos.size()>0){
//                        String cover_img = videos.get(0).get("cover_img");
//                        ArrayList<Map<String, String>> cover_imgs = JSONUtils.getListMapByJson(cover_img);
//                        if (cover_imgs.size()>0){
//                            Map<String, String> map1 = cover_imgs.get(0);
//                            pic_right = map1.get("u");
//                        }
//                    }
//                }
//            }
//        }


//            if (TextUtils.equals("0", type)) {
                ReplyListBean.ListBean msgReplyListBean = new ReplyListBean.ListBean();
                msgReplyListBean.setId(reply_res_id);
                msgReplyListBean.setPost_id(post_id);
                msgReplyListBean.setContent(reply_res_content);
                msgReplyListBean.setLike_num("0");
                msgReplyListBean.setIs_like(0);
                msgReplyListBean.setReply_num("0");
                msgReplyListBean.setIs_god("0");
                msgReplyListBean.setDate(datetime);
                ReplyListBean.ListBean.UserBeanX userBeanX = new ReplyListBean.ListBean.UserBeanX();
                userBeanX.setSex(a_sex);
                userBeanX.setAvator(a_avator);
                userBeanX.setNickname(a_nickname);
                userBeanX.setUid(a_uid);
                msgReplyListBean.setUser(userBeanX);

                List<ReplyListBean.ListBean.PicsBean> picsBeans = new ArrayList<>();
                if (!TextUtils.isEmpty(reply_res_pics)) {
                    ArrayList<Map<String, String>> picss = JSONUtils.getListMapByJson(reply_res_pics);
                    for (int i = 0; i < picss.size(); i++) {
                        Map<String, String> o = picss.get(i);
                        String w = o.get("w");
                        String h = o.get("h");
                        String u = o.get("u");
                        String is_gif = o.get("is_gif");

                        ReplyListBean.ListBean.PicsBean picsBean = new ReplyListBean.ListBean.PicsBean();
                        picsBean.setW(w);
                        picsBean.setH(h);
                        picsBean.setU(u);
                        picsBean.setIs_gif(is_gif);
                        picsBeans.add(picsBean);
                    }
                }

                msgReplyListBean.setPics(picsBeans);
                if (list.size() > 2 && list.get(1).getId()!= msgReplyListBean.getId()){
                    for (int i=0;i<list.size();i++){
                        if (list.get(i).getId()==msgReplyListBean.getId()){
                            list.remove(i);
                            break;
                        }
                    }
                    list.add(1,msgReplyListBean);
                    adapter.notifyDataSetChanged();
                }else{
//                    list.add(1,msgReplyListBean);
//                    adapter.notifyDataSetChanged();
                }
//            }




            type = "";
            item = null;

            replyBar.showReplyBar(true,true);
        }
    }

    private void initReplyBar(){
        ReplyBarBase replyBarBase = findViewById(R.id.reply_bar_base);
        replyBar = findViewById(R.id.reply_bar);
        replyBarBase.setOnReplyBarBaseClickListener(new ReplyBarBase.ReplyBarBaseClickListener() {
            @Override
            public void clickText() {
                replyBar.showReplyBar(true,true);
            }

            @Override
            public void clickImg() {
                replyBar.showReplyBar(true,false);
                replyBar.addPhoto();
            }
        });
        comment_rl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                replyBar.setOnTouch();
                return false;
            }
        });
        //发布成功消息回调
        replyBar.setOnReplyBarLisener(new ReplyBar.ReplyBarReplySuccessLisener() {
            @Override
            public void success(CDetailsListBean data) {

                ReplyListBean.ListBean replyListBean = new ReplyListBean.ListBean();

//                    JSONObject jsonObject = new JSONObject(data);
                String id = data.getId();
                String post_id = data.getPost_id();//jsonObject.optString("post_id");
                String content = data.getContent();//jsonObject.optString("content");
                String like_num = data.getLike_num();// jsonObject.optInt("like_num");
                int is_like = data.getIs_like();// jsonObject.optInt("is_like");
                String is_god =data.getIs_god();// jsonObject.optString("is_god");
                String reply_num = data.getReply_num();// jsonObject.optString("reply_num");
                String date = data.getDate();// jsonObject.optString("date");

//                    JSONObject user = jsonObject.optJSONObject("user");
                String uid = data.getUser().getUid();// user.optString("uid");
                String nickname = data.getUser().getNickname();// user.optString("nickname");
                String avator = data.getUser().getAvator();// user.optString("avator");
                String sex = data.getUser().getSex();// user.optString("sex");

                ReplyListBean.ListBean.UserBeanX userBeanX = new ReplyListBean.ListBean.UserBeanX();
                userBeanX.setUid(uid);
                userBeanX.setNickname(nickname);
                userBeanX.setAvator(avator);
                userBeanX.setSex(sex);

//                    JSONArray jsonArray = jsonObject.optJSONArray("pics");
                List<ReplyListBean.ListBean.PicsBean> pics = new ArrayList<>();
                for (int i=0;i<data.getPics().size();i++){
//                        JSONObject o = (JSONObject) jsonArray.get(i);
                    RecommPictureBean recommPictureBean = data.getPics().get(i);
                    String w = recommPictureBean.getW();// o.optString("w");
                    String h = recommPictureBean.getH();// o.optString("h");
                    String u = recommPictureBean.getU();// o.optString("u");
                    String is_gif ;

                    if (recommPictureBean.isIs_gif()){
                        is_gif = "0";
                    }else{
                        is_gif = "1";
                    }

                    ReplyListBean.ListBean.PicsBean picsBean = new ReplyListBean.ListBean.PicsBean();
                    picsBean.setW(w);
                    picsBean.setH(h);
                    picsBean.setU(u);
                    picsBean.setIs_gif(is_gif);
                    pics.add(picsBean);
                }

                replyListBean.setId(id);
                replyListBean.setPost_id(post_id);
                replyListBean.setContent(content);
                replyListBean.setLike_num(like_num);
                replyListBean.setIs_like(is_like);
                replyListBean.setIs_god(is_god);
                replyListBean.setReply_num(reply_num);
                replyListBean.setDate(date);
                replyListBean.setUser(userBeanX);
                replyListBean.setPics(pics);

                list.add(1,replyListBean);
                if (adapter != null){
                    adapter.notifyDataSetChanged();
                }
                tv_title.setText(String.valueOf(Integer.parseInt(replynum)+1)+"条回复");
                replynum=String.valueOf(Integer.parseInt(replynum)+1);

            }
        });

        replyBar.setReplyBar(1,post_id,reply_id,uid);
    }

    private void initView() {
        tv_title=findViewById(R.id.tv_title);
        comment_rl = findViewById(R.id.comment_rl);
        iv_closecha = findViewById(R.id.iv_closecha);
        tv_nodata = findViewById(R.id.tv_nodata);
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(false);//启用刷新
        comment_rl.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        comment_rl.setItemAnimator(new DefaultItemAnimator());

        adapter = new CommentDetailAdapter(list,getThis());
        adapter.setOnZanDataListener(new CommentDetailAdapter.OnZanDataListener() {
            @Override
            public void zanData(String id, int Postion,boolean iszan) {
                initOnZanHttp(id,Postion,iszan);
            }
        });
        comment_rl.setAdapter(adapter);

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                initData(false);
            }
        });
        iv_closecha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.v_headerback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initData(final boolean isRefresh) {

        if (isRefresh){
            page = 1;
        }else{
            page ++;
        }

        String POSTDEL = HttpConfig.REPLY_REPLY;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("post_id", post_id);//帖子id
        treeMap.put("page", String.valueOf(page));
        treeMap.put("pagesize", "15");
        treeMap.put("reply_id", reply_id);//评论的id
        HttpClient.getInstance().postRxAndroidAES(POSTDEL, treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {

                        if (TextUtils.equals("200", responseData.getCode())) {


                            final ReplyListBean postDetalData = new Gson().fromJson(responseData.getData(), ReplyListBean.class);
                            if (isRefresh){
                                ReplyListBean.ReplyInfoBean reply_info = postDetalData.getReply_info();
                                ReplyListBean.ListBean bean= new ReplyListBean.ListBean();
                                bean.setContent(reply_info.getContent());
                                bean.setDate(reply_info.getDate());
                                bean.setIs_god(reply_info.getIs_god());
                                bean.setIs_like(reply_info.getIs_like());
                                bean.setPics(reply_info.getPics());
                                bean.setLike_num(reply_info.getLike_num());
                                bean.setUser(reply_info.getUser());
                                bean.setReply_num(reply_info.getReply_num());
                                bean.setId(reply_info.getId());
                                list.add(bean);
                                replynum=bean.getReply_num();
                                tv_title.setText(bean.getReply_num()+"条回复");

                                if (postDetalData.getList().size() == 0){
                                    tv_nodata.setVisibility(View.GONE);
                                }
                            }
                            list.addAll(postDetalData.getList());
                            if (postDetalData.getHas_more()==1){
                                refreshLayout.finishLoadMore(true);
                            }else{
                                refreshLayout.setNoMoreData(true);
                            }

                            if (adapter == null) {


                            } else {
                                adapter.notifyDataSetChanged();
                            }

                            msgType();

                        } else {
                            showToast(responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("数据请求失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
    private void initOnZanHttp(String id, final int Position, final boolean iszan){
        if (!SPUtils.isLogined()){
            Intent intent = new Intent(getContext(), LoginRegistActivity.class);
            startActivity(intent);
            return;
        }
        String POSTDEL = HttpConfig.MEMBERLIKE;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("id", id);//id
        treeMap.put("status",!iszan?"1":"2" );
        treeMap.put("type", "2");
        HttpClient.getInstance().postRxAndroidAES(POSTDEL, treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {

                        if (TextUtils.equals("200", responseData.getCode())) {
                            String body = responseData.getBody();
                            try {
                                JSONObject object =new JSONObject(body);
                                String data =object.getString("data");
                                if (data.equals("成功")){
                                    String like_num = list.get(Position ).getLike_num();
                                    if (iszan){
                                        list.get(Position).setIs_like(0);
                                        if (!like_num.contains("w") && !like_num.contains("k")){
                                            like_num = (Long.valueOf(like_num)-1)+"";
                                            list.get(Position).setLike_num(like_num);
                                        }

                                    }else {
                                        list.get(Position).setIs_like(1);
                                        if (!like_num.contains("w") && !like_num.contains("k")){
                                            like_num = (Long.valueOf(like_num)+1)+"";
                                            list.get(Position).setLike_num(like_num);
                                        }
                                    }
                                    if (Position==0){//通知上一个页面改变状态
                                        ReplyListBean.ListBean bean = list.get(Position);
                                        EventBus.getDefault().post(bean);
                                    }
                                    adapter.notifyDataSetChanged();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            showToast(responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("数据请求失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (replyBar != null){
            replyBar.onActivityResult(requestCode,resultCode,data);
        }
    }
}
